<template>
  <div>
    <the-table
      :data="tabledata"
      :pageInfo="queryInfo"
      :total="total"
      @pageInfoChange="pageInfoChange"
      @handleAdd="add"
      :layout="['addBtn', 'search', 'column']"
      :columns="columns"
      @changeColumn="changeColumn"
      @search="search"
      @clearInput="initList"
    >
      <!-- 表格区 -->
      <el-table-column label="用户ID" prop="id" v-if="columns[0].show">
      </el-table-column>
      <el-table-column label="账号" prop="logName" v-if="columns[1].show">
      </el-table-column>
      <el-table-column
        label="用户类型"
        prop="roleInfo.label"
        v-if="columns[2].show"
      >
      </el-table-column>
      <el-table-column label="昵称" prop="name" v-if="columns[3].show">
      </el-table-column>
      <el-table-column label="邮箱" prop="email" v-if="columns[4].show">
      </el-table-column>
      <el-table-column label="性别" prop="sex" v-if="columns[5].show">
      </el-table-column>
      <!-- 操作区域 -->
      <el-table-column label="操作" width="200px" v-if="columns[6].show">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            style="color: #409eff"
            @click="edit(scope.row)"
          >
            <el-icon class="el-input__icon"><edit /></el-icon> 编辑
          </el-button>
          <el-button
            size="small"
            type="text"
            style="color: #f56c6c"
            @click="removeById(scope.row.id)"
          >
            <el-icon class="el-input__icon"><delete /></el-icon> 删除
          </el-button>
        </template>
      </el-table-column>
    </the-table>

    <!-- 新增 -->
    <el-dialog
      title="新增"
      v-model="addVisible"
      width="50%"
      @close="resetForm(ruleFormRef)"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="form"
        :rules="formRules"
        ref="ruleFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="logName">
          <el-input v-model="form.logName"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            show-password
            v-model="form.password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobilePhone">
          <el-input v-model="form.mobilePhone"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份" prop="role">
          <el-select v-model="form.role">
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.identity"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="upload-demo"
            name="multipartFile"
            action="http://119.23.218.131:9504/mall/file/upload"
            :limit="1"
            :on-remove="addAfficheRemove"
            :on-success="addAfficheSuccess"
            :file-list="addAfficheList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传一张jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirm(ruleFormRef)"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {
  pageList,
  pageNameList,
  addReq,
  update,
  remove,
} from "@/api/User/account";
import { allList } from "@/api/Authority/role";
import { addLogs } from "@/api/Home/Home";
import { reactive, toRefs, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { ElForm } from "element-plus";
import TheTable from "@/components/common/TheTable.vue";
export default {
  components: { TheTable },
  setup() {
    const ruleFormRef = ref<InstanceType<typeof ElForm>>();

    // 发布新公告表单规则
    const formRules = {
      name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
      logName: [{ required: true, message: "请输入登录名", trigger: "blur" }],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      email: [
        { required: true, message: "请输入邮箱", trigger: "blur" },
        {
          pattern:
            /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g,
          message: "请输入正确的邮箱",
          trigger: "blur",
        },
      ],
      sex: [{ required: true, message: "请选择性别", trigger: "change" }],
      mobilePhone: [
        { required: true, message: "请输入手机号", trigger: "blur" },
        {
          pattern:
            /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
          message: "请输入正确的手机号码",
          trigger: "blur",
        },
      ],
    };
    const state = reactive({
      queryInfo: {
        pageNum: 1,
        pageSize: 5,
        isShow: true,
        placeholder: "请输入用户名进行搜索",
      },
      columns: [
        { name: "用户Id", show: true },
        { name: "账号", show: true },
        { name: "用户类型", show: true },
        { name: "昵称", show: true },
        { name: "邮箱", show: true },
        { name: "性别", show: true },
        { name: "操作", show: true },
      ],
      // 统计公告的总数量
      total: 0,
      addVisible: false,
      addClosed: false,
      tabledata: [],
      addAfficheList: [],
      form: {
        id: "",
        logName: "",
        headImage: "",
        email: "",
        name: "",
        mobilePhone: "",
        password: "",
        role: 0,
      },
      isAdd: true,
      roleList: [],
    });
    function search(searchText) {
      pageNameList(
        state.queryInfo.pageNum,
        state.queryInfo.pageSize,
        searchText
      ).then((res) => {
        state.tabledata = res.data.users.users.content;
        state.total = res.data.users.users.totalElements;
      });
    }
    function initList() {
      pageList(state.queryInfo.pageNum, state.queryInfo.pageSize).then(
        (res) => {
          state.tabledata = res.data.users.users.content;
          state.total = res.data.users.users.totalElements;
        }
      );
    }
    function initAdm() {
      allList().then((res) => {
        if (res.status !== 200) ElMessage.error("请求权限列表出错！");
        state.roleList = res.data.roles.roles;
      });
    }

    // 改变表单栏显示隐藏状态
    function changeColumn(columns) {
      state.columns = columns;
    }
    function addAfficheSuccess(response, file, fileList) {
      if (response.statusCode !== 20000) {
        return ElMessage.error(response.message);
      }
      // 将json格式的数据转化为对象
      let resData = JSON.parse(response.data);
      state.form.headImage = resData.url;
    }
    function addAfficheRemove(file, fileList) {
      state.form.headImage = "";
    }
    function add() {
      state.isAdd = true;
      state.form = {
        id: "",
        logName: "",
        headImage: "",
        email: "",
        name: "",
        mobilePhone: "",
        password: "",
        role: 0,
      };
      state.addVisible = true;
    }
    function edit(obj) {
      state.isAdd = false;
      Object.assign(state.form, obj);
      state.addVisible = true;
    }
    function confirm(formEl: InstanceType<typeof ElForm> | undefined) {
      if (!formEl) return;
      formEl.validate((valid) => {
        if (valid) {
          if (state.isAdd) {
            addReq(state.form).then((res) => {
              // console.log(res);
              if (res.data.ret == 0) {
                ElMessage.success("添加成功");
                state.addVisible = false;
              }
              addLogs({
                userId: window.sessionStorage.getItem("userId"),
                behavior: "新增了《" + state.form.logName + "》用户",
              });
              initList();
            });
          } else {
            update(state.form.id, state.form).then((res) => {
              // console.log(res);
              if (res.data.ret == 0) {
                ElMessage.success("修改成功");
                state.addVisible = false;
              }
              addLogs({
                userId: window.sessionStorage.getItem("userId"),
                behavior: "修改了《" + state.form.logName + "》用户",
              });
              initList();
            });
          }
        } else {
          return false;
        }
      });
    }
    const resetForm = (formEl: InstanceType<typeof ElForm> | undefined) => {
      if (!formEl) return;
      formEl.clearValidate();
    };
    async function removeById(id) {
      const confirmResult = await ElMessageBox.confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err: any) => err);
      if (confirmResult === "confirm") {
        await remove(id).then((res) => {
          if (res.data.ret == 0) {
            ElMessage.success(res.data.msg);
            initList();
          } else {
            ElMessage.error(res.data.msg);
          }
        });
      }
    }
    // 分页数据改变
    function pageInfoChange(type: string, newValue: number) {
      console.log(type, newValue);
      if (type === "size") state.queryInfo.pageSize = newValue;
      else if (type === "page") state.queryInfo.pageNum = newValue;
      initList();
    }
    initList();
    initAdm();
    return {
      ...toRefs(state),
      pageInfoChange,
      removeById,
      confirm,
      edit,
      addAfficheRemove,
      addAfficheSuccess,
      initList,
      search,
      changeColumn,
      add,
      ruleFormRef,
      resetForm,
      formRules,
    };
  },
};
</script>

<style lang="less" scoped></style>
